package pc.nick.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * tomcat启动类
 * 创建socket连接，监听端口，浏览器有连接就丢给线程池去执行
 */
public class MyTomcat {
    public static void main(String[] args) {
         MyTomcat myTomcat = new MyTomcat();
         myTomcat.startServer();
    }

    private void startServer() {
        System.out.println("服务器准备启动");
        //TODO: 在这里加入一个xml解析模块，读取server.xml文件,获取端口号
        int port = 8888;
        ServerSocket serverSocket = null;
        try{
            serverSocket = new ServerSocket(port);
            System.out.println("服务器启动成功，监听：" + serverSocket.getLocalPort()+"端口");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(port + "被占用，服务器启动失败");
            // TODO : 自动选择另一个tcp的空闲端口
            System.exit(0);
        }

        // 建立一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        while(true){
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                System.out.println("客户端"+ socket.getRemoteSocketAddress() + "连接上来了");
                // 启动线程来处理这个客户端的请求与响应
                ThreadTask threadTask = new ThreadTask(socket);
                executorService.execute(threadTask); // 线程池执行
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("客户端" + socket.getRemoteSocketAddress() + "掉线了");
            }
        }

    }
}